package middlewares

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

// SaveAccessLog
//
//	@Description: 保存访问日志
//	@param c
func SaveAccessLog(c *gin.Context) {
	start := time.Now().UnixNano()
	// 创建一个自定义的 ResponseWriter
	rw := &responseBodyWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
	c.Writer = rw

	c.Next()
	path := c.Request.URL.Path
	method := c.Request.Method
	query := c.Request.URL.Query()
	fmt.Println("请求路径---------->>>>:", path)
	fmt.Println("请求方式---------->>>>:", method)
	fmt.Println("请求参数---------->>>>:", query)
	fmt.Println("响应数据---------->>>>:", rw.body.String())
	fmt.Println("状态响应码---------->>>>:", rw.Status())
	fmt.Println("请求耗时---------->>>>:", time.Now().UnixNano()-start, "纳秒")
}

// responseBodyWriter 自定义的 ResponseWriter 结构体
type responseBodyWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

// Write 重写 Write 方法以捕获响应体
func (rw *responseBodyWriter) Write(b []byte) (int, error) {
	rw.body.Write(b)
	return rw.ResponseWriter.Write(b)
}

// WriteString 重写 WriteString 方法以捕获响应体
func (rw *responseBodyWriter) WriteString(s string) (int, error) {
	rw.body.WriteString(s)
	return rw.ResponseWriter.WriteString(s)
}
